package com.zh.core.controller;

import com.zh.core.entity.User;
import com.zh.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by zhaohui on 2019/8/4
 * Description:
 */
@Controller
@RequestMapping("/lar")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登陆页面
     *
     * @return
     */
    @RequestMapping(value = "/login")
    public String login() {
        return "login";
    }

    /**
     * 注册页面
     *
     * @return
     */
    @RequestMapping(value = "/register")
    public String register() {
        return "register";
    }

    /**
     * 主页面
     *
     * @return
     */
    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }

    /**
     * 登陆
     *
     * @return
     */
    @RequestMapping(value = "/loginAction", method = RequestMethod.POST)
    public String loginAction(String username, String password, Model model, HttpSession session) {
        User user = userService.queryUserByUsernameAndPassword(username, password);
        if (user != null) {
            // 将用户对象添加到Session
            session.setAttribute("USER_SESSION", user);
            // 跳到主页面
//            return "redirect:/lar/main";
            // 跳转到客户信息列表页面
            return "redirect:/lar/customerList";
        }
        model.addAttribute("msg", "账号或密码错误,请重新输入!");
        return "login";
    }

    /**
     * 注册
     *
     * @param username
     * @param password
     * @param phone
     * @param email
     * @param model
     * @return
     */
    @RequestMapping(value = "/registerAction", method = RequestMethod.POST)
    public String registerAction(String username, String password, String phone, String email, Model model) {
        //如果用户名已经存在，给出提示信息
        if (userService.usernameExist(username)) {
            model.addAttribute("msg", "用户名已经存在,请重新输入!");
            return "register";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
        //用户信息成功写入数据库,跳转到登陆页面，并给出提示信息
        if (userService.createUser(user) > 0) {
            model.addAttribute("msg", "注册成功，请登陆!");
            return "login";
        } else { //用户信息写入失败，给出提示信息
            model.addAttribute("msg", "注册失败,请稍后再试!");
            return "register";
        }
    }

}
